<!--
 * @Descripttion: 资源管理
 * @version:
 * @Author: 穆宏宇
 * @Date: 2020-09-28 18:38
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-04 16:21:47
-->
<template>
	<div class="bigDiv">
		<div class="page-box">
			<el-form label-width="80px">
				<el-row>
					<div class="topNav">
						<el-button type="text" icon="el-icon-plus" @click="insertResources">新增</el-button>
					</div>
					<el-col :span="8">
						<el-form-item label="菜单名称" style="margin-bottom:0px;">
							<el-input placeholder="请输入菜单名称" size="small" v-model="search" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<!-- 表格 -->
			<el-table border :data="tableData" row-key="id" :expand-row-keys="expandRow"
				:tree-props="{children: 'children'}" :max-height="650" style="width: 100%;margin-top: 20px;"
				v-loadmore="loadMore">
				<el-table-column prop="label" label="菜单名称"></el-table-column>
				<!-- <el-table-column prop="httpMethod" label="请求类型">
          <template slot-scope="scope">
            <span>{{ strHttpType(scope.row.httpMethod) }}</span>
          </template>
        </el-table-column> -->
				<!--      <el-table-column prop="address" label="是否有效"></el-table-column>-->
				<el-table-column prop="path" label="连接" align="center"></el-table-column>
				<el-table-column prop="sortValue" label="排序（升序）" align="center">
				</el-table-column>
				<!--      <el-table-column prop="" label="数据权限">-->
				<!--        <template slot-scope="scope">-->
				<!--          <span>{{scope.row.createTime.substr(0,10) }}</span>-->
				<!--        </template>-->
				<!--      </el-table-column>-->
				<!-- <el-table-column prop="authorityType" label="菜单类型">
			<template slot-scope="scope">
			 <span>{{scope.row.authorityType == 1?'采购':'后台管理'}}</span>
		   </template>
		</el-table-column> -->
				<el-table-column fixed="right" label="操作" align="center" width="260">
					<template slot-scope="scope">
						<div class="centered-content">
							<el-tooltip content="编辑" placement="top">
								<el-button @click="editorEvent(scope.row)" type="primary" size="mini" plain><i
										class="iconfont el-icon-edit"></i></el-button>
							</el-tooltip>
							<el-tooltip content="删除" placement="top">
								<el-button @click="deleteEvent(scope.row)" type="warning" size="mini" plain><i
										class="iconfont el-icon-delete"></i></el-button>
							</el-tooltip>
							<el-tooltip content="资源管理" placement="top">
								<el-button @click="currentResouresMenu(scope.row)" type="primary" size="mini" plain><i
										class="iconfont el-icon-plus"></i></el-button>
							</el-tooltip>
						</div>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<!--  新增/编辑 角色-->
		<el-dialog :title="arrDialogTitle[dialogType]" :visible.sync="dialogVisible" width="60%"
			:before-close="handleClose" :close-on-click-modal="false" :close-on-press-escape="false">
			<el-form ref="resourcesForm" :model="resourcesForm" label-width="120px" :rules="rules">
				<!-- <el-form-item label="上级菜单:" prop="parentIds">
          <el-cascader
              v-model="resourcesForm.parentIds"
              :options="resourceArray"
              :props="cascaderProps"
              clearable
              filterable></el-cascader>
        </el-form-item> -->
				<!-- {{resourcesForm}} -->
				<!-- <el-form-item label="分配">
					<el-checkbox-group v-model="resourcesForm.authoritys" @change="changeType" style="height:40px;">
						<el-checkbox :label="1">采购端</el-checkbox>
						<el-checkbox :label="2">后台管理端</el-checkbox>
						<el-checkbox :label="4">项目经理端</el-checkbox>
						<el-checkbox :label="8">供应商端</el-checkbox>
					</el-checkbox-group>
				</el-form-item> -->
				<el-form-item label="菜单名称:" prop="label">
					<el-input v-model="resourcesForm.label" placeholder="请输入菜单名称"></el-input>
				</el-form-item>
				<!-- <el-form-item label="请求类型:" prop="httpMethod">
          <el-select
              :disabled="resourcesForm.authorityType === '0' || resourcesForm.authorityType === 'MENU'"
              v-model="resourcesForm.httpMethod"
                     placeholder="请选择请求类型">
            <el-option
                v-for="item in httpMethodArr"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item> -->
				<!-- <el-form-item label="菜单类型:" prop="group">
          <el-select :disabled="resourcesForm.authorityType === 'RESOURCE' || resourcesForm.authorityType === '1'" v-model="resourcesForm.group" placeholder="请选择菜单类型">
            <el-option label="前台菜单" value="1"></el-option>
            <el-option label="后台菜单" value="2"></el-option>
          </el-select>
        </el-form-item> -->
				<el-form-item label="链接" prop="path">
					<el-input v-model="resourcesForm.path" placeholder="请输入链接"></el-input>
				</el-form-item>
				<el-form-item label="排序（升序）:" prop="sortValue">
					<el-input type="number" v-model="resourcesForm.sortValue" placeholder="请输入排序（升序）"></el-input>
				</el-form-item>
				<!-- <el-form-item label="菜单图标:" prop="icon">
          <el-input v-model="resourcesForm.icon" placeholder="请输入菜单图标"></el-input>
        </el-form-item> -->
				<!--        <el-form-item label="页签标题:" prop="code">-->
				<!--          <el-input v-model="roleForm.cyeqiode" placeholder="请输入页签标题"></el-input>-->
				<!--        </el-form-item>-->
				<!-- <el-form-item label="菜单类型:" prop="authorityType" v-if="dialogType===0">
          <el-radio v-model="resourcesForm.authorityType" label="0" @change="changeRadio">菜单</el-radio>
          <el-radio v-model="resourcesForm.authorityType" label="1" @change="changeRadio">权限</el-radio>
        </el-form-item> -->
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="cancelEvent('resourcesForm')">取 消</el-button>
				<el-button type="primary" @click="dialogSubmit('resourcesForm')">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import {
		addResource,
		putResource,
		deleteResource,
		getAuthorityResourceList,
		getMenuList,
		insertAuthMenu,
		editAuthMenu,
		deleteAuthMenuById
	} from '@/api/admin.api'
	export default {
		name: 'resources-manager',
		components: {},
		data() {
			return {
				search: '',
				// 表格数据
				// tableData: [],
				expandRow: [],
				dialogTitle: '',
				dialogVisible: false,
				httpMethodArr: [{
						value: '0',
						label: 'GET'
					},
					{
						value: '2',
						label: 'POST'
					},
					{
						value: '3',
						label: 'PUT'
					},
					{
						value: '4',
						label: 'PATCH'
					},
					{
						value: '5',
						label: 'DELETE'
					}
				],
				arrDialogTitle: ['新增资源基本信息', '编辑资源基本信息'],
				dialogType: 0, // 0 新增， 1编辑
				resourcesForm: {
					parentIds: [],
					label: '',
					httpMethod: '',
					group: '',
					path: '',
					sortValue: '',
					icon: '',
					authorityType: '0',
					authority: "6",
					authoritys: [4, 2]
				},
				rules: {
					// parentIds: [{ required: true, message: '请选择上级菜单', trigger: 'change' }],
					label: [{
						required: true,
						message: '请输入菜单名称',
						trigger: 'blur'
					}],
					httpMethod: [{
						required: true,
						message: '请选择请求类型',
						trigger: 'change'
					}],
					group: [{
						required: false,
						message: '请选择菜单类型',
						trigger: 'change'
					}],
					path: [{
						required: true,
						message: '请输入链接',
						trigger: 'blur'
					}],
					sortValue: [{
						required: true,
						message: '请输入排序（升序）',
						trigger: 'blur'
					}],
					// icon:[{ required: true, message: '请输入菜单图标', trigger: 'blur'}],
					authorityType: [{
						required: true,
						message: '请选择菜单类型',
						trigger: 'change'
					}]
				},
				arrDsType: [],
				resourceArray: [],
				treeList: [], //资源数据列表
				cascaderProps: {
					label: 'label',
					children: 'children',
					value: 'id',
					checkStrictly: true
				},
				// menuIds:[],
				dataObjById: {},
				expandedKeys: [],
				authorityId: '', // 资源ID
				arrAllData: [], //列表数据
				pageSize: 10, // 每页显示条数
				currentPage: 0, // 当前页数
				total: 0, // 列表数据总数
				currTotal: 0, // 当前加载条数
				list: [{
					name: '采购端'
				}, {
					name: '后台管理端'
				}, {
					name: '项目经理端'
				}, {
					name: '供应商端'
				}]

			}
		},
		watch: {},
		computed: {
			strHttpType() {
				return function(type) {
					let label = ''
					this.httpMethodArr.forEach(item => {
						if (item.value === type) {
							label = item.label
							return false
						}
					})
					return label
				}
			},
			// // 表格高度
			// maxHeightNow () {
			//   // const height = window.innerHeight
			//   return 500
			// },
			tableData: function() {
				const searchValue = this.search
				if (searchValue) {
					// let treeData = this.resourceArray
					let treeData = this.arrAllData
					let handleTreeData = this.handleTreeData(treeData, searchValue)
					this.setExpandRow(handleTreeData)
					return handleTreeData
				}
				return this.resourceArray
			}
		},
		directives: { // 自定义私有指令
			'loadmore': {
				bind: (el, binding) => {
					let p = 0
					let t = 0
					let down = true
					let selectWrap = el.querySelector('.el-table__body-wrapper')
					selectWrap.addEventListener('scroll', function() {
						//判断是否向下滚动
						p = this.scrollTop
						if (t < p) {
							down = true
						} else {
							down = false
						}
						t = p
						//判断是否到底
						const sign = 3
						const scrollDistance = this.scrollHeight - this.scrollTop - this.clientHeight
						// console.log('scrollHeight:' + this.scrollHeight)
						// console.log('scrollTop:'+this.scrollTop)
						// console.log('clientHeight:'+ this.clientHeight)

						if (scrollDistance <= sign && down) {
							binding.value()
						}
					})
				}
			}
		},
		created() {},
		mounted() {
			// 角色授权菜单
			this.getResourceListFn()
		},
		methods: {
			changeType(e) {
				let code = 0;
				console.log(e)
				e.forEach(row => {
					code = (code | row)
				})
				// console.log(code)
				this.resourcesForm.authoritys = e;
				this.resourcesForm.authority = code;

			},
			// 加载更多
			loadMore() {
				if (this.currTotal >= this.total && this.currTotal !== 0) {
					return
				}
				const start = this.currentPage * this.pageSize
				const range = this.pageSize * this.currentPage
				// 每页条数>=10
				if (this.total - range >= this.pageSize) {
					for (let i = start, max = start + this.pageSize; i < max; i++) {
						this.resourceArray.push(this.arrAllData[i])
						this.currTotal++
					}
				}
				// <10条
				else {
					for (let i = start, max = this.total; i < max; i++) {
						this.resourceArray.push(this.arrAllData[i])
						this.currTotal++
					}
				}
				this.currentPage++
			},
			//  树形表格过滤
			handleTreeData(treeData, searchValue) {
				if (!treeData || treeData.length === 0) {
					return []
				}
				const array = []
				for (let i = 0; i < treeData.length; i += 1) {
					let match = false
					for (let pro in treeData[i]) {
						if (typeof(treeData[i][pro]) == 'string') {
							match |= treeData[i][pro].includes(searchValue)
							if (match) break
						}
					}
					if (this.handleTreeData(treeData[i].children, searchValue).length > 0 || match) {
						array.push({
							...treeData[i],
							children: this.handleTreeData(treeData[i].children, searchValue)
						})
					}
				}
				return array
			},
			// 将过滤好的树形数据展开
			setExpandRow(handleTreeData) {
				if (handleTreeData.length) {
					for (let i of handleTreeData) {
						this.expandRow.push(i.id)
						if (i.children.length) {
							this.setExpandRow(i.children)
						}
					}
				}
			},
			// 改变菜单类型
			changeRadio(value) {
				if (value === '0') {
					this.resourcesForm.httpMethod = '0'
					this.rules.group[0].required = true
				} else {
					this.resourcesForm.httpMethod = ''
					this.rules.group[0].required = false
				}
			},
			/**
			 * @description 查询用户授权列表
			 * @author 穆宏宇
			 * @date 2020-09-28 08:52:28
			 * @param
			 * @return
			 * */
			getResourceListFn() {
				const id = this.$tools.localRead('userId')
				getMenuList(id).then(res => {
					// 获取不包含授权资源名称为空的数据
					let array = res.filter(item => item.label)
					let dataArr = this.treeList = array
					// 按照id的顺序重新排列
					dataArr.map(item => {
						this.dataObjById[item['id']] = item
					})

					this.arrAllData = this.getTreeData2(dataArr, ['0', null])
					this.total = this.arrAllData.length
					// 递归转树型
					this.resourceArray = []
					this.currTotal = 0
					this.currentPage = 0

					this.loadMore()
				})
			},
			/**
			 * @description 递归转树型
			 * @author 穆宏宇
			 * @date 2020-09-28 10:40:59
			 * @param data 树型列表
			 * @param defaultRoot 0/null 为跟节点
			 * @param parent 父节点
			 * @return
			 * */
			getTreeData2(data, parent) {
				let self = this
				let tree = []
				let temp
				// 遍历数组，通过parentId，获取父节点对象，如果不存在，则为根节点
				data.map(item => {
					if (parent.indexOf(item.parentId) > -1) {
						temp = self.getTreeData2(data, [item.id])
						// 插入子节点数组children
						if (temp.length > 0) {
							item.children = temp
						} else {
							item.children = ''
						}
						// 插入父节点对象parent
						if (self.dataObjById[item.parentId]) {
							let {
								id,
								label,
								parentId
							} = self.dataObjById[item.id]
							item.parent = {
								id,
								label,
								parentId
							}
						} else {
							item.parent = {}
						}
						tree.push(item)
					}
				})
				return tree
			},
			/**
			 * @description 编辑角色弹窗
			 * @author 穆宏宇
			 * @date 2020-09-27 16:00:05
			 * @param
			 * @return
			 * */
			editorEvent(row) {
				this.dialogVisible = true
				this.$nextTick(() => {
					let code = row.authority;
					let c = code.toString(2)
					let left = c.length - 1
					let authority = [];
					for (let index = 0; index < c.length; index++, left--) {
						let a = (c[index] << left)
						if (a > 0) {
							authority.push(a)
						}
					}
					console.log(authority)

					this.dialogType = 1
					this.authorityId = row.id
					for (let item in this.resourcesForm) {
						this.$set(this.resourcesForm, item, row[item])
					}
					if (this.resourcesForm.authorityType === 'RESOURCE') {
						this.rules.group[0].required = false
					} else {
						this.rules.group[0].required = true
					}
					this.resourcesForm.parentIds = []
					this.resourcesForm.authoritys = authority
					// 查询当前ID的查询所以父级数据
					const parents = this.getParent(this.resourceArray, row.parentId)
					// 当去ID的所有父级id
					const parentIds = parents.map(item => item.id)
					this.$set(this.resourcesForm, 'parentIds', parentIds)





					this.$forceUpdate()
				})
			},
			// 查询当前ID的查询所以父级数据
			getParent(data2, nodeId2) {
				let arrRes = []
				if (data2.length == 0) {
					if (!!nodeId2) {
						arrRes.unshift(data2)
					}
					return arrRes
				}
				let rev = (data, nodeId) => {
					for (let i = 0, length = data.length; i < length; i++) {
						let node = data[i]
						if (node.id == nodeId) {
							arrRes.unshift(node)
							rev(data2, node.parentId)
							break
						} else {
							if (!!node.children) {
								rev(node.children, nodeId)
							}
						}
					}
					return arrRes
				}
				arrRes = rev(data2, nodeId2)
				return arrRes
			},
			/**
			 * @description 删除
			 * @author 穆宏宇
			 * @date 2020-09-27 16:17:08
			 * @param
			 * @return
			 * */
			deleteEvent(row) {
				this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					deleteAuthMenuById({
						id: row.id
					}).then(() => {
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
						// 角色授权菜单
						this.getResourceListFn()
					})

				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			/**
			 * @description 插入资源
			 * @author 穆宏宇
			 * @date 2020-09-28 20:17:00
			 * @param
			 * @return
			 * */
			insertResources() {
				this.dialogType = 0
				this.dialogVisible = true
				this.$refs['resourcesForm'].resetFields()
				this.rules.group[0].required = false
			},
			/**
			 * @description 新增当前资源下的目录
			 * @author 穆宏宇
			 * @date 2020-09-28 19:16:08
			 * @param
			 * @return
			 * */
			currentResouresMenu(row) {
				this.dialogVisible = true
				this.$nextTick(() => {
					this.dialogType = 0
					this.$refs['resourcesForm'].resetFields()
					this.rules.group[0].required = false
					// 查询当前ID的查询所以父级数据
					const parents = this.getParent(this.resourceArray, row.parentId)
					// 当去ID的所有父级id
					const parentIds = parents.map(item => item.id)
					parentIds.push(row.id)
					this.$set(this.resourcesForm, 'parentIds', parentIds)
					this.$forceUpdate()
				})

			},
			// 关闭弹窗
			handleClose(done) {
				this.$refs['resourcesForm'].resetFields()
				done();
			},
			cancelEvent(formName) {
				this.$refs[formName].resetFields()
				this.dialogVisible = false

			},
			// 提交表单
			dialogSubmit(formName) {
				// 验证表单
				this.$refs[formName].validate((valid) => {
					if (!valid) {
						return false
					}
				})
				if (this.resourcesForm.parentIds && this.resourcesForm.parentIds.length > 0) {
					const parentId = this.resourcesForm.parentIds.pop()
					this.resourcesForm['parentId'] = parentId
				}
				// 新增资源信息
				if (this.dialogType === 0) {
					insertAuthMenu(this.resourcesForm).then(() => {
						this.$message({
							type: 'success',
							message: '添加成功!'
						});
						this.refreshList(formName)
					})
				}
				// 编辑资源信息
				if (this.dialogType === 1) {
					editAuthMenu({
						...this.resourcesForm,
						id: this.authorityId
					}).then(() => {
						this.$message({
							type: 'success',
							message: '修改成功!'
						});
						this.refreshList(formName)
					})
				}
			},
			// 刷新列表
			refreshList(formName) {
				this.$refs[formName].resetFields()
				this.dialogVisible = false
				// 角色授权菜单
				this.getResourceListFn()
			}
		}
	}
</script>

<style scoped lang="scss">
	.page-box {
		padding: 20px;
		background: white;
		height: calc(100vh - 120px);

		&-newbtn {
			text-align: right;
			padding: 0 20px 20px 0;
		}

		/*.el-pagination {*/
		/*  padding-top: 20px;*/
		/*  text-align: right;*/
		/*}*/
	}

	.centered-content {
		display: flex;
		justify-content: center;
		align-items: center;
	}
	/*::v-deep .el-table--scrollable-y .el-table__body-wrapper {*/
	/*  overflow-y: scroll !important;*/
	/*}*/
</style>